package socket

import (
	"bytes"
	"github.com/gorilla/websocket"
	"log"
)

var (
	newline = []byte{'\n'}
	space   = []byte{' '}
)

// Client is a middleman between the websocket connection and the hub.
type Client struct {
	hub *Hub

	// The websocket connection.
	conn *websocket.Conn

	// Buffered channel of outbound messages.
	send chan []byte

	group string
	id    string
}

type WebSocketMessage struct {
	Type  string      `json:"type"`
	Data  interface{} `json:"data"`
	Error error       `json:"error,omitempty"`
}

func (c *Client) Send(message []byte) {
	writer, err := c.conn.NextWriter(websocket.BinaryMessage)
	if err != nil {
		//slog.Error("发生错误", "发送数据", err.Error())
		//c.hub.unregister <- c
		return
	}

	if _, err := writer.Write(message); err != nil {
		//slog.Error("发生错误", "发送数据", err.Error())
		return
	}
}

func (c *Client) read() {
	for {
		_, message, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("error: %v", err)
			}
			break
		}
		message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
		if c.hub.handle != nil {
			c.hub.handle(c, message)
		}
	}
}
